<template>
  <!-- 搜索框 -->
  <view class="search-box">
    <uni-search-bar v-model="searchValue" :focus="true" @input="input" @cancel="cancel" @clear="clear"
      bgColor="#ffffff">
    </uni-search-bar>
  </view>
  <!-- 搜索结果 -->
  <uni-section v-for="(item,index) in searchResults" :title="item.name" titleFontSize="16px" :subTitle="item.ar[0].name"
    subTitleFontSize="12px" style="margin: 6px 0px;" v-if="searchResults.length !== 0" @click="onChange(item)">
    <template v-slot:right>
      <uni-icons type="headphones" size="30"></uni-icons>
    </template>
  </uni-section>
  <!-- 搜索历史 -->
  <view v-else>
    <!-- 有历史记录 -->
    <view v-if="history.length != 0">
      <uni-section title="搜索历史" class="history-bg">
        <template v-slot:right>
          <uni-icons type="trash-filled" size="16px" @click="clearHistory()"></uni-icons>
        </template>
      </uni-section>
      <view class="history-list">
        <uni-tag v-for="(item,index) in history" :key="index" :text="item" :circle="true"
          @click="historySearch(item)" />
      </view>
    </view>
    <!-- 无历史记录 -->
    <view v-else style="display: flex;justify-content: space-evenly;margin-top: 20px;">
      <text>暂无记录 快去搜索吧~</text>
    </view>
  </view>

</template>

<script>
  import {
    useStore
  } from 'vuex'
  import {
    ref,
    computed
  } from 'vue'
  import {
    searchRusAPI
  } from '../../api/index.js'
  import {
    onReachBottom
  } from '@dcloudio/uni-app'
  // 请求搜索结果
  const getSearchList = async (searchValue, searchResults, pageNum, historyList) => {
    if (searchValue.value.trim().length == 0) {
      searchResults.value = []
      return
    }
    // 发起请求
    const data = await searchRusAPI(searchValue.value, 30 * pageNum)
    if (data.data.code == 400 && searchResults.value.length !== 0) {
      uni.$showMsg('没有更多了')
      return
    }
    if (data?.data?.result?.songs.length == 0) {
      uni.$showMsg('搜索数据条数为空 请重新输入')
      searchResults.value = []
    }
    searchResults.value = data.data.result.songs
    saveHistory(historyList, searchValue)
  }
  // 保存搜索记录
  const saveHistory = (historyList, searchValue) => {
    const set = new Set(historyList.value)
    set.delete(searchValue.value)
    set.add(searchValue.value)
    historyList.value = Array.from(set)
    // 调用 uni.setStorageSync(key, value) 将搜索历史记录持久化存储到本地
    uni.setStorageSync('historyList', JSON.stringify(historyList.value))
  }
  export default {
    setup() {
      const store = useStore()
      // 搜索内容
      const searchValue = ref('')
      // 搜索结果列表
      const searchResults = ref([])
      // 历史记录 先从缓存中获取，没有就设置为空
      const historyList = ref(JSON.parse(uni.getStorageSync('historyList') || '[]'))
      const history = computed(() => {
        return [...historyList.value].reverse()
      })
      // 清空历史记录
      const clearHistory = async () => {
        const data = await uni.showModal({
          title: '提示',
          content: '请确认操作无误，清除后无法恢复！！！'
        }).catch(err => err)
        if (data && data.confirm) {
          historyList.value = []
          store.commit("upHistoryList", '[]')
        }
      }
      // 点击历史 进行搜索
      const historySearch = (item) => {
        searchValue.value = item
        getSearchList(searchValue, searchResults, pageNum, historyList)
      }
      // 延时器的 timerId
      const timer = ref(null)
      // 页面
      let pageNum = 1
      // 点击叉叉小图标 清空内容
      const clear = (res) => {
        searchValue.value = ''
      }
      // 点击取消 关闭搜索框 清空内容
      const cancel = (res) => {
        searchValue.value = ''
      }
      // 内容改变
      const input = (res) => {
        clearTimeout(timer.value)
        timer.value = setTimeout(() => {
          searchValue.value = res
          pageNum = 1
          getSearchList(searchValue, searchResults, pageNum, historyList)
        }, 200)
      }
      // 点击搜索结果跳转到播放页
      const onChange = (item) => {
        uni.navigateTo({
          url: '/subpkg/play/play?id=' + item.id
        })
        console.log(item)
      }
      // 触底再加载
      onReachBottom(() => {
        pageNum += 1
        getSearchList(searchValue, searchResults, pageNum, historyList)
      })
      return {
        clear,
        cancel,
        input,
        searchResults,
        history,
        clearHistory,
        historySearch,
        searchValue,
        onChange
      };
    }
  }
</script>

<style lang="scss">
  .history-bg {
    background-color: #f7f7f700;
  }

  .uni-section {
    background-color: #fff0 !important;
  }

  .uni-searchbar {
    /* #ifndef APP-NVUE */
    display: flex;
    /* #endif */
    flex-direction: row;
    position: relative;
    padding: 16rpx;
  }

  .search-box {
    position: sticky;
    top: -8px;
    z-index: 999;
  }

  .history-list {
    display: flex;
    flex-wrap: wrap;

    .uni-tag {
      margin: 5px 5px;
    }
  }
</style>
